﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Common.IProviders;
using System.Web;
using System.Configuration;
using CSP.Common.Tools;
using CSP.Common.Factories;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace CSP.Common.Providers
{
    public class RenRenApiProvider : OtherApiProvider
    {
        public override string AccessToken
        {
            get
            {
                if (HttpContext.Current.Session["OtherAccessToken"] != null)
                {
                    return HttpContext.Current.Session["OtherAccessToken"].ToString();
                }
                return "";
            }
            set
            {
                HttpContext.Current.Session["OtherAccessToken"] = value;
            }
        }

        /// <summary>
        /// 人人APIUid
        /// </summary>
        public string RenRenUid
        {
            get
            {
                return ConfigurationManager.AppSettings["RenRenUid"];
            }
        }

        /// <summary>
        /// 人人AppKey
        /// </summary>
        public string RenRenAppKey
        {
            get
            {
                return ConfigurationManager.AppSettings["RenRenAppKey"];
            }
        }

        /// <summary>
        /// 人人AppSecret
        /// </summary>
        public string RenRenAppSecret
        {
            get
            {
                return ConfigurationManager.AppSettings["RenRenAppSecret"];
            }
        }

        /// <summary>
        /// 人人操作API Uri
        /// </summary>
        public string RenRenApiUri {
            get
            {
                return ConfigurationManager.AppSettings["RenRenApiUri"];
            }
        }


        /// <summary>
        /// 人人API登陆跳转授权
        /// </summary>
        public string RenRenAuthorizeUri
        {
            get
            {
                return ConfigurationManager.AppSettings["RenRenAuthorize"];
            }
        }

        /// <summary>
        /// 人人API获取获取授权Uri
        /// </summary>
        public string RenRenAccessTokenUri
        {
            get
            {
                return ConfigurationManager.AppSettings["RenRenAccessToken"];
            }
        }


        /// <summary>
        /// 发布人人API
        /// </summary>
        public string RenRenPublishInfo
        {
            get
            {
                return ConfigurationManager.AppSettings["RenRenPublishInfo"];
            }
        }

        /// <summary>
        /// 分享人人API
        /// </summary>
        public string RenRenShareUri
        {
            get
            {
                return ConfigurationManager.AppSettings["RenRenShare"];
            }
        }

        /// <summary>
        /// 获取人人API用户信息
        /// </summary>
        public string RenRenUserInfo
        {
            get
            {
                return ConfigurationManager.AppSettings["RenRenUserInfo"];
            }
        }

        /// <summary>
        /// 营销标题
        /// </summary>
        private string MarketingMsg {
            get
            {
                return ConfigurationManager.AppSettings["MarketingMsg"];
            }
        }

        /// <summary>
        /// 营销描述
        /// </summary>
        private string MarketingDescription
        {
            get 
            {
                return ConfigurationManager.AppSettings["MarketingDescription"];
            }
        }

        /// <summary>
        /// 用户Id
        /// </summary>
        public override string Uid
        {
            get
            {

                if (HttpContext.Current.Session["otherUid"] != null)
                {
                    return HttpContext.Current.Session["otherUid"].ToString();
                }
                else
                {
                    return "";
                }

            }
            protected set
            {
                HttpContext.Current.Session["otherUid"] = value;
            }
        }

        /// <summary>
        /// 请求API登陆授权
        /// </summary>
        /// <returns></returns>
        public override void RequestApiAuthorization(string backUrl)
        {

            string requestUrl = RenRenAuthorizeUri + "?client_id=" + RenRenAppKey + "&response_type=code&scope=publish_feed+publish_share&redirect_uri=" + HttpContext.Current.Server.UrlEncode(backUrl);
            HttpContext.Current.Response.Redirect(requestUrl);
        }

        /// <summary>
        /// 根据请求的Code值，和重定向的Uri获取用户基本信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="redirectUri"></param>
        /// <param name="openId">openId可为空</param>
        /// <returns></returns>
        public override Dictionary<string, string> GetUserInfo(string code, string redirectUri, string openId = "")
        {
            GetAccessToken(code, redirectUri);
            Dictionary<string, string> result = GetUserInfoByAccessToken(AccessToken, Uid);
            Uid = result["uid"];
            return result;
        }

        /// <summary>
        ///Api事件处理管道“关注/API”
        /// </summary>
        /// <param name="isPublish"></param>
        /// <param name="isAttention"></param>
        public override void EventHandling(bool isPublish, bool isAttention)
        {
            if (isPublish)
            {
                PublishInfo();
            }

        }

        /// <summary>
        /// 获取权限令牌AccessToken
        /// </summary>
        /// <param name="code">人人Code</param>
        /// <param name="redirectUri">回调的链接地址</param>
        /// <returns></returns>
        private Dictionary<string, string> GetAccessToken(string code, string redirectUri)
        {
            string redirecturl = "client_id=" + RenRenAppKey + "&client_secret=" + RenRenAppSecret + "&grant_type=authorization_code" +
                    "&code=" + code + "&redirect_uri=" + HttpContext.Current.Server.UrlEncode(redirectUri) +  "&method=" + RenRenPublishInfo;
            string json = CommonTool.MakePostByUrlAndPostData(RenRenAccessTokenUri, redirecturl);
            Dictionary<string, string> accessToken = AnalysisRenRenAccessToken(json);
            string access_token = accessToken["access_token"];
            AccessToken = access_token;
            return accessToken;
        }

        /// <summary>
        /// 根据AccessToken获取用户信息
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetUserInfoByAccessToken(string accessToken, string uid)
        {
            string redirecturl = RenRenApiUri;
            string requestParm = "v=1.0&format=JSON&access_token=" + accessToken + "&method=" + RenRenUserInfo + "&fields=uid,name,sex,star,zidou,birthday,email_hash,tinyurl,headurl,mainurl,vip";
            string json = CommonTool.MakePostByUrlAndPostData(redirecturl,requestParm);
           
            Dictionary<string, string> result = AnalysisRenRenGetUserInfo(json);
            
            return result;
        }

        private void PublishInfo()
        {
            string renrenPublishInfo = RenRenApiUri;
            string marketingMsg = HttpContext.Current.Server.UrlEncode(ConfigurationManager.AppSettings["MarketingMsg"].ToString());
            //request = renrenPublishInfo + "?status=" + marketingMsg+"&access_token=" + accessToken ;
            string requestParm = "v=1.0&format=JSON&access_token=" + AccessToken + "&method=" + RenRenPublishInfo + "&description=" + HttpContext.Current.Server.UrlEncode(MarketingDescription) + "&name=" + MarketingMsg + "&url=" + HttpContext.Current.Server.UrlEncode("http://www.tongshuya.com") ;
            string json = CommonTool.MakePostByUrlAndPostData(renrenPublishInfo, requestParm);
            Dictionary<string, string> jsonDic = AnalysisRenRenResult(json);

            if(Convert.ToInt32(jsonDic["post_id"].ToString())<=0)
            {
                ILoggerProvider logger = LoggerFactory.GetErrorLogger();
                logger.Warn("(警告)人人API发布新鲜事错误:" + json + "  [openId]:" + Uid + "[Token]:" + AccessToken);   
            }
        }

        //private void Attention()
        //{
        //    string request;
        //    //关注
        //    string renrenAttention = RenRenAttentionUri;
        //    string uid = RenRenUid;
        //    request = "oauth_consumer_key=" + RenRenAppKey + "&oauth_version=2.a" + "&openid=" + Uid + "&scope=all" + "&access_token=" + AccessToken + "&format=json" + "&clientip=" + CommonTool.GetIP() + "&name=" + RenRenUid + "&access_token=" + AccessToken;
        //    string json = CommonTool.MakePostByUrlAndPostData(renrenAttention, request);
        //    Dictionary<string, string> jsonDic = AnalysisRenRenResult(json);
        //    if (jsonDic["ret"] != "0")
        //    {
        //        ILoggerProvider logger = LoggerFactory.GetErrorLogger();
        //        logger.Warn("(警告)人人API关注:" + json + "  [openId]:" + Uid + "[Token]:" + AccessToken);
        //    }
        //}


        /// <summary>
        /// 解析人人API获取授权
        /// </summary>
        /// <param name="json"></param>
        private Dictionary<string, string> AnalysisRenRenAccessToken(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);
            
            //权限token
            string access_token = obj["access_token"].ToString().Replace("\"", "");
            string expires_in = obj["expires_in"].ToString().Replace("\"", "");
            string refresh_token = obj["refresh_token"].ToString().Replace("\"", "");
            string scope = obj["scope"].ToString().Replace("\"", "");
            dic.Add("access_token", access_token);
            dic.Add("expires_in", expires_in);
            dic.Add("scope", scope);
            dic.Add("refresh_token", refresh_token);
            return dic;
        }

        /// <summary>
        /// 解析人人API的用户基本信息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private Dictionary<string, string> AnalysisRenRenGetUserInfo(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JArray obj = (JArray)JsonConvert.DeserializeObject(json);

            
            //uid 	int 	表示用户id
            string uid = obj[0]["uid"].ToString().Replace("\"", "").Trim();
            //name 	string 	表示用户名
            string name = obj[0]["name"].ToString().Replace("\"", "").Trim();
            //sex 	int 	表示性别，值1表示男性；值0表示女性
            string sex = obj[0]["sex"].ToString().Replace("\"", "").Trim();
            //star 	int 	表示是否为星级用户，值“1”表示“是”；值“0”表示“不是”
            string star = obj[0]["star"].ToString().Replace("\"", "");
            //zidou 	int 	表示是否为vip用户，值1表示是；值0表示不是
            string zidou = obj[0]["zidou"].ToString().Replace("\"", "");
            //vip 	int 	表示是否为vip用户等级，前提是zidou节点必须为1
            string vip = obj[0]["vip"].ToString().Replace("\"", "");
            //birthday 	string 	表示出生时间，格式为：yyyy-mm-dd，需要自行格式化日期显示格式。注：年份60后，实际返回1760-mm-dd；70后，返回1770-mm-dd；80后，返回1780-mm-dd；90后，返回1790-mm-dd
            string birthday = obj[0]["birthday"].ToString().Replace("\"", "");
            //email_hash 	string 	用户经过验证的email的信息字符串：email通过了connect.registerUsers接口。字符串包含的email经过了crc32和md5的编码
            string email_hash = obj[0]["email_hash"].ToString().Replace("\"", "");
            //tinyurl 	string 	表示头像链接 50*50大小
            string tinyurl = obj[0]["tinyurl"].ToString().Replace("\"", "");
            //headurl 	string 	表示头像链接 100*100大小
            string headurl = obj[0]["headurl"].ToString().Replace("\"", "");
            //mainurl 	string 	表示头像链接 200*200大小 
            string mainurl = obj[0]["mainurl"].ToString().Replace("\"", "");

            //uid 	int 	表示用户id
            dic.Add("uid", uid);
            //name 	string 	表示用户名
            dic.Add("name", name);
            //sex 	int 	表示性别，值1表示男性；值0表示女性
            dic.Add("sex", sex);
            //star 	int 	表示是否为星级用户，值“1”表示“是”；值“0”表示“不是”
            dic.Add("star", star);
            //zidou 	int 	表示是否为vip用户，值1表示是；值0表示不是
            dic.Add("zidou", zidou);
            //vip 	int 	表示是否为vip用户等级，前提是zidou节点必须为1
            dic.Add("vip", vip);
            //birthday 	string 	表示出生时间，格式为：yyyy-mm-dd，需要自行格式化日期显示格式。注：年份60后，实际返回1760-mm-dd；70后，返回1770-mm-dd；80后，返回1780-mm-dd；90后，返回1790-mm-dd
            dic.Add("birthday", birthday);
            //email_hash 	string 	用户经过验证的email的信息字符串：email通过了connect.registerUsers接口。字符串包含的email经过了crc32和md5的编码
            dic.Add("email_hash", email_hash);
            //tinyurl 	string 	表示头像链接 50*50大小
            dic.Add("tinyurl", tinyurl);
            //headurl 	string 	表示头像链接 100*100大小
            dic.Add("headurl", headurl);
            //mainurl 	string 	表示头像链接 200*200大小 
            dic.Add("mainurl", mainurl);
           
            return dic;
        }

        /// <summary>
        /// 返回请求结果返回值；
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private Dictionary<string, string> AnalysisRenRenResult(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);

            //返回码
            string post_id = obj["post_id"].ToString().Replace("\"", "");
            dic.Add("post_id", post_id);

            return dic;
        }
    }
}
